import PIL.Image
import numpy
import pylab as pl
import sys
from scikits.learn.pca import RandomizedPCA

img_size = (71,123)
n_components = int(sys.argv[2])

def read_im(name):
    pic = PIL.Image.open(name)
    pic = pic.resize(img_size)
    return numpy.array(pic)
def read_x(img_set):
    x = read_im(img_set[0])
    x = x.ravel()
    ##only one is needed
    #for name in img_set[1:]:
        #img = read_im(name)
        #img = img.ravel()
        #x = numpy.vstack((x, img))
    #x -= x.mean(axis=1)[:,numpy.newaxis]
    x -= x.mean()
    return x

def pca(x):
    #result=solver.fit
    p = RandomizedPCA(n_components=n_components, whiten=True).fit(x)
    return p

def print_im(im):
    im = im.reshape((img_size[1], img_size[0]))
    pl.imshow(im)
    pl.show()


if __name__ == '__main__':

    #img load in x
    #for debug
    img_set=[sys.argv[1]]
    x =read_x(img_set)

    # to train
    #p = pca(x)

    # to load
    p = numpy.load('pca.npy')[0]

    # to predict
    t = p.transform(x)#t is a quantity x n_components array [][][]...

    file_out=open('pca_svm','w')

    #step=quantity[0]
    #num=0
    #for i in range(t.shape[0]):
    for j in range(0,t.shape[0]):
        file_out.write(str(j+1+50)+':'+str(t[j])+' ')#+50 for stack with ODCR file
    file_out.write('\n')

    # to save
    numpy.save('pca', [p])
